function JsonOBJ() {
    this.id = null;
    this.majorname = null;
    this.classname = null;
    this.studentname = null;
    this.startTime = null;
    this.endTime = null;
    this.teachername = null;
    this.requestReason = null;
    this.rejectReason = null;
    this.authStatus = null;
    this.requestTime = null;
}

var pageNo = 1;     //当前页
var pageSize = 3;   //每页记录数
var pageCount = 1;
var tabCurrent = 0; //当前标签，待审批，代发，历史记录
var islogin = 1;
var isSubmit = 0;
var dataJson;  //查询参数

$(function () {

    if ($("#type").attr("value") == 0) {
        $("#btn-apply-yes").click(function () {
            approveList(0);
            return false;
        });
        $(".btn-apply-not button").click(function () {
            var i = 0;
            var checked = new Array();
            $("img[id]").each(function () {
                if ($(this).attr("check_type") == 1) {
                    checked.push($(this).attr('id'));
                    i++;
                }
            });
            if (i == 0) {
                layer.msg("至少勾选一条数据", {time: 1000});
            } else {
                sessionStorage.setItem('checked', checked);
                window.location = "apply.not_weApprove_teacher.html";
            }
            return false;
        });
        queryData();
    } else if ($("#type").attr("value") == 5) {
        $('.btn-replace').click(function () {
            var i = 0;
            var checkedStu = new Array();
            $("img[id]").each(function () {
                if ($(this).attr("check_type") == 1) {
                    checkedStu.push([$(this).attr('name'), $(this).attr('id')]);
                    i++;
                }
            });
            if (i == 0) {
                layer.msg("至少勾选一条数据", {time: 1000});
            } else {
                sessionStorage.setItem('checkedStu', checkedStu);
                window.location = 'apply.detail_weReplace_teacher.html';
            }
            return false;

        });
        queryData();
    } else {
        $(".search-btn").click(function () {
            pageNo = 1;
            queryData();
            return false;
        });
        $("select").change(function () {
            pageNo = 1;
            $("#type").attr("value", $("select").val());
            queryData();
        });
        $("#date-start").focusout(function () {
            pageNo = 1;
            queryData();
        });
        $("#date-end").focusout(function () {
            pageNo = 1;
            queryData();
        });
        queryData();
    }

});

function check(str) {
    if (str != null && str != "" || str == 0) {
        if (str.errorcode != undefined) {
            if (str.errorcode == 1) {
                if (islogin == 1) {
                    layer.msg(str.errormessage, {time: 1000});
                    // window.location.href = "/door/front_end/pc/teacher/login_pc_teacher.html";
                    islogin = 0;
                }
            }
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function queryData() {
    sessionStorage.removeItem('checked');
    sessionStorage.removeItem('checkedStu');
    sessionStorage.removeItem('one_record');
    sessionStorage.removeItem('type');

    tabCurrent = $("#type").attr("value");
    var sdate = $("#date-start").val();
    var edate = $("#date-end").val();
    var stuName = $(".seek-box").val();

    if (typeof(sdate) == "undefined" || sdate == "") {
        sdate = "1970-01-01 00:00:00";
    }
    if (typeof(edate) == "undefined" || edate == "") {
        edate = "2160-01-01 00:00:00";
    }
    if (typeof(stuName) == "undefined") {
        stuName = "";
    }
    var startDate = new Date(sdate.replace("T", " "));
    var endDate = new Date(edate.replace("T", " "));
    dataJson = {
        startDate: DateUtils.format(startDate, "yyyy-MM-dd HH:mm:ss"),
        endDate: DateUtils.format(endDate, "yyyy-MM-dd HH:mm:ss"),
        stuName: stuName,
        pageNo: pageNo,
        pageSize: pageSize,
        type: tabCurrent
    };
    if ($("#type").attr("value") == 5) {
        queryDataOfStu();
    } else {
        getDataOfRecord();
    }
}

function queryDataOfStu() {
    $.ajax({
        async: true,
        type: 'POST',
        url: '/door/front/teacher/getCurTeaStus',
        data: {
            pageSize: 500,
            pageNo: pageNo
        },
        cache: false,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        beforeSend: function (xhr) {
        },
        success: function (data, textStatus, xhr) {
            if (check(data)) {
                if (data.itemCount == 0) {
                    layer.msg("没有数据", {time: 1000});
                }
                pageCount = Math.floor((data.itemCount + pageSize - 1) / pageSize);
                setTableBTN();
                setDataOfStuList(data.list);
                toggleChecked();
            }
        },
        error: function (xhr, textStatus, errorInfo) {
        },
        complete: function (xhr, textStatus) {
        }
    });
}

function getDataOfRecord() {//带参分页查询函数
    $.ajax({
        async: true,
        type: 'POST',
        url: '/door/front/teacher/apply',
        data: dataJson,
        cache: false,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        beforeSend: function (xhr) {
        },
        success: function (data, textStatus, xhr) {
            if (check(data)) {
                if (data.itemCount == 0) {
                    layer.msg("没有数据", {time: 1000});
                }
                pageCount = Math.floor((data.itemCount + pageSize - 1) / pageSize);
                setTableBTN();
                setDataOfList(data.list);
                toggleChecked();
            }
        },
        error: function (xhr, textStatus, errorInfo) {
        },
        complete: function (xhr, textStatus) {
        }
    });
}

function setDataOfList(records) {
    $(".record .item").remove();
    var str = '';

    for (var i = 0; i < records.length; i++) {
        var status_str = null;
        var status_class = null;
        switch (records[i].authStatus) {
            case 0 :
                status_str = "审批中";
                status_class = "state-ing";
                break;
            case 1 :
                status_str = "审批通过";
                status_class = "state-yes";
                break;
            case 2 :
                status_str = "审批驳回";
                status_class = "state-no";
                break;
            case 3 :
                status_str = "撤销";
                status_class = "state-cancel";
                break;
        }

        str += '<div class="item"><div class="checkBox"><img src="../../../images/img_xuanzhe_01.png" alt="" check_type=0 id=' +
            records[i].id + '></div><a href="#" onclick="toDetail(this)"><table class="apply-table-we text-center"><tr><td class="apply-td1"><p>' +
            records[i].classname + '</p><p>' +
            records[i].studentname + '</p></td><td class="apply-td2"><label>请假时长：</label><p>' +
            DateUtils.format(new Date(records[i].startTime), "yyyy-MM-dd HH:mm:ss") + '</p><p>至</p><p>' +
            DateUtils.format(new Date(records[i].endTime), "yyyy-MM-dd HH:mm:ss") + '</p></td><td class="apply-td3"><label>请假原因：</label><p class="apply-reason">' +
            records[i].requestReason + '</p></td><td class="apply-td4"><p class="' +
            status_class + '">' +
            status_str + '</p></td></tr></table></a></div>';
        // str += '<div class="apply-item text-center"><div><div class="checkBox fl">' +
        //     '<img src="../../../images/img_xuanzhe_01.png" alt="" class="check" check_type=0 id=' +
        //     records[i].id + '></div><p>' +
        //     records[i].classname + '</p><p>' +
        //     records[i].studentname + '</p></div><div><label>请假时长：</label><p>' +
        //     DateUtils.format(new Date(records[i].startTime), "yyyy-MM-dd HH:mm:ss") + '</p><p>至</p><p>' +
        //     DateUtils.format(new Date(records[i].endTime), "yyyy-MM-dd HH:mm:ss") + '</p><p class="' +
        //     status_class + '">' +
        //     status_str + '</p></div><div><label>请假原因：</label><div class="reason">' +
        //     records[i].requestReason + '</div><a href="apply.detailsPC_teacher.html"><p class="to-detail">查看详情>> </p></a></div></div>';
    }
    // $("#pageCount").text(pager.pageCount);
    $(".page-nav").before(str);
}

function setDataOfStuList(students) {
    $(".replace-name-list").empty();
    var str = '';

    for (var i = 0; i < students.length; i++) {
        str += '<li><div class="fl"><img src="../../../images/img_xuanzhe_01.png" alt="" check_type=0 id="' +
            students[i].code + '" name="' +
            students[i].name + '"></div><span>' +
            students[i].name + '<br/>' +
            students[i].code + '</span></li>';
        // str += '<li class="col-sm-3 student-name"><ul class="student-area"><li class="fl checkBox margin-cancel">' +
        //     '<img src="../../../images/img_xuanzhe_01.png" alt="" class="check" check_type=0 id=' +
        //     students[i].code + '></li><li><h4 class="name-border">' +
        //     students[i].name + '<br/>' +
        //     students[i].code + '</h4></li></ul></li>'
    }

    $(".replace-name-list").html(str);
}

function setTableBTN() {
    $("#page").unbind();

    $("#page option").remove();

    for (var i = 1; i <= pageCount; i++) {
        if (i != pageNo)
            $("#page").append("<option>" + i + "</option>");
        else
            $("#page").append("<option selected=true>" + i + "</option>");
    }

    $("#page").change(function (i) {
        console.log($("#page").find("option:selected").text());
        pageNo = parseInt($("#page").find("option:selected").text());
        queryData();
    });

    $(".page-nav span").each(function (i) {
        if (i == 1) {//上一页按钮
            this.onclick = function () {
                if (pageNo > 1) {
                    pageNo--;
                    queryData();
                } else {
                    layer.msg("当前是第一页", {time: 1000});
                }
            };
        } else if (i == 2) {//下一页按钮
            this.onclick = function () {
                if (pageNo < pageCount) {
                    pageNo++;
                    queryData();
                } else {
                    layer.msg("当前是最后一页", {time: 1000});
                }
            };
        } else if (i == 0) {
            this.onclick = function () {
                pageNo = 1;
                queryData();
            };
        } else if (i == 3) {
            this.onclick = function () {
                pageNo = pageCount;
                queryData();
            };
        }
    });
}

function toggleChecked() {
    if ($("#type").attr("value") == 5) {
        $(".fl img").each(function () {
            $(this).click(function () {
                if ($(this).attr("check_type") == 0) {
                    $(this).attr("check_type", 1);
                    $(this).attr("src", "../../../images/img_xuanzhe_02.png")
                } else {
                    $(this).attr("check_type", 0);
                    $(this).attr("src", "../../../images/img_xuanzhe_01.png")
                }
            })
        });
        $(".allCheck img").click(function () {
            if ($(this).attr("check_type") == 0) {
                $(this).attr("check_type", 1);
                $(this).attr("src", "../../../images/img_xuanzhe_02.png");
                $(".fl img").each(function () {
                    $(this).attr("check_type", 1);
                    $(this).attr("src", "../../../images/img_xuanzhe_02.png")
                });
            } else {
                $(this).attr("check_type", 0);
                $(this).attr("src", "../../../images/img_xuanzhe_01.png");
                $(".fl img").each(function () {
                    $(this).attr("check_type", 0);
                    $(this).attr("src", "../../../images/img_xuanzhe_01.png");
                });
            }
        });
    } else {
        $(".checkBox img").each(function () {
            $(this).click(function () {
                if ($(this).attr("check_type") == 0) {
                    $(this).attr("check_type", 1);
                    $(this).attr("src", "../../../images/img_xuanzhe_02.png")
                } else {
                    $(this).attr("check_type", 0);
                    $(this).attr("src", "../../../images/img_xuanzhe_01.png")
                }
            })
        });
        $(".allCheck img").click(function () {
            if ($(this).attr("check_type") == 0) {
                $(this).attr("check_type", 1);
                $(this).attr("src", "../../../images/img_xuanzhe_02.png");
                $(".checkBox img").each(function () {
                    $(this).attr("check_type", 1);
                    $(this).attr("src", "../../../images/img_xuanzhe_02.png")
                });
            } else {
                $(this).attr("check_type", 0);
                $(this).attr("src", "../../../images/img_xuanzhe_01.png");
                $(".checkBox img").each(function () {
                    $(this).attr("check_type", 0);
                    $(this).attr("src", "../../../images/img_xuanzhe_01.png");
                });
            }
        });
    }

}

function approveList(type) {
    var checkIds = new Array();
    $("img[id]").each(function () {
        if ($(this).attr("check_type") == 1) {
            var js = new JsonOBJ();
            js.id = $(this).attr("id");
            if (type == 0) {
                js.authStatus = 1;
                js.rejectReason = "";
            } else {
                js.authStatus = 2;
                js.rejectReason = $("#caused").val();
            }
            checkIds.push(js);
        }
    });
    if (checkIds.length == 0) {
        layer.msg("至少勾选一条数据", {time: 1000});
    } else {
        $.ajax({
            url: "/door/front/teacher/approve?" + new Date().getTime(),
            type: "post",
            data: JSON.stringify(checkIds),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            async: false,
            success: function (str) {
                if (check(str)) {
                    if (str == checkIds.length) {
                        layer.msg("批准成功", {time: 1000});
                        pageNo = 1;
                        queryData();
                    } else {
                        layer.msg("失败" + (checkIds.length - parseInt(str)) + "条！", {time: 1000});
                        pageNo = 1;
                        queryData();
                    }
                }
            }
        });
    }
}

function toDetail (a) {
    sessionStorage.setItem('type', $("#type").attr("value"));
    sessionStorage.setItem('one_record', $(a).prev().children("img").attr('id'));
    window.location = "apply.weDetail_teacher.html";
}